package com.artifact.mit.mypoint.async;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.ContextWrapper;
import android.os.AsyncTask;

import com.artifact.mit.mypoint.model.api.Catalogue;
import com.artifact.mit.mypoint.model.api.Catalogue.CatalogueDetail;
import com.artifact.mit.mypoint.util.APICall;

public class MenuAsyncTask extends AsyncTask<String, Void, Map<String, ArrayList<String>>> {

	private Context menuAsyncContext;
	
	public MenuAsyncTask(Context context) {
		menuAsyncContext = context;
	}
	
	@Override
	protected Map<String, ArrayList<String>> doInBackground(String... arg0) {
		Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
		Catalogue catalogue = APICall.catalogue(menuAsyncContext);
		if (catalogue != null) {
			CatalogueDetail catalogueDetail[] = catalogue.getCatalogueDetails();
			for (int x = 0; x < catalogueDetail.length; x++) {
				if (map.get(catalogueDetail[x].getDpName()) != null) {
					map.get(catalogueDetail[x].getDpName()).add(catalogueDetail[x].getCtName());
				} else {
					ArrayList<String> arrayList = new ArrayList<String>();
					arrayList.add(catalogueDetail[x].getCtName());
					map.put(catalogueDetail[x].getDpName(), arrayList);
				}
			}
			try{
				ContextWrapper cw = new ContextWrapper(menuAsyncContext);
				File directory = cw.getDir("dat", Context.MODE_PRIVATE);
				File file = new File(directory, "menu.ser");
				FileOutputStream f = new FileOutputStream(file);
				ObjectOutputStream s = new ObjectOutputStream(f);
				s.writeObject(map);
				s.close();
			}catch(Throwable e){
				e.printStackTrace();
			}
			return map;
		} else {
			return null;
		}
	}
}
